package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ManageService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    //查询手机端用户信息列表
    public PageResult findByPage(Integer page,Integer pageSize) {
     IPage iPage = userInfoApi.findAll(page,pageSize);
       // 当前页  每页条数  总数 数据列表  page实现ipage接口，，可从ipage里获取总记录条数和记录
     return new PageResult(page,pageSize,iPage.getTotal(),iPage.getRecords());
    }
  //查询用户基本资料
    public UserInfo findById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        return  info;
    }
  //查询用户发布的视频列表
    public PageResult findVideosById(Integer page, Integer pageSize, Long uid) {
        //调api查询，返回分页数据，（分页列表，总数）
      PageResult pageResult = videoApi.selectById(page,pageSize,uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();
        if (CollUtil.isEmpty(videoList)){
           return pageResult;
       }
        UserInfo info = userInfoApi.findById(uid);
        List<VideoVo> videoVos = new ArrayList<>();
        for (Video video : videoList) {
            VideoVo vo = VideoVo.init(info, video);
            videoVos.add(vo);
        }
        pageResult.setItems(videoVos);
        return pageResult;
    }
    //查询用户动态列表
    public PageResult findMovement(Integer status, Integer page, Integer pageSize, Long uid) {
       PageResult pageResult =  movementApi.findMovementList(status,page,pageSize,uid);
        List<Movement> items = (List<Movement>) pageResult.getItems();
        if(CollUtil.isEmpty(items)){
            return  pageResult;
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> ids = userInfoApi.findIds(userIds);
       // UserInfo info = userInfoApi.findById(uid);
        List<MovementsVo> movementsVos = new ArrayList<>();
        for (Movement item : items) {
            Long id = item.getUserId();
            UserInfo info = ids.get(id);
            MovementsVo vo = MovementsVo.init(info, item);
            movementsVos.add(vo);
        }
        pageResult.setItems(movementsVos);
        return pageResult;
    }
}
